<template>
  <el-dialog
    :title="isEdit ? '编辑角色' : '新增角色'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="50%"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item prop="name" label="角色名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="onConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addRoleApi, updateRoleApi } from '@/api/setting'
export default {
  props: {
    // 控制弹框弹起和关闭
    visible: {
      type: Boolean,
      default: false
    },
    // 编辑状态标志
    isEdit: {
      type: Boolean,
      default: false
    },
    // 当前要编辑的数据
    row: {
      type: Object
    }
  },
  watch: {
    // 监听visible判断当前是否是编辑状态
    visible(val) {
      if (val && this.isEdit) {
        this.form = this.row
      }
    }
  },
  data() {
    return {
      // 存储表单数据
      form: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 处理弹框关闭逻辑
    handleClose() {
      this.form = {
        name: '',
        description: ''
      }
      // this.$refs.form.resetFields()
      this.$emit('update:visible', false)
    },
    // 点击确定按钮
    async onConfirm() {
      await this.$refs.form.validate()
      // 校验通过，进行新增逻辑处理
      if (this.isEdit) {
        await updateRoleApi(this.row.id, this.form)
      } else {
        await addRoleApi(this.form)
      }
      this.$message.success('操作成功')
      this.$emit('success')
      this.handleClose()
    }
  }
}
</script>

<style>
</style>